package com.iqiyi.dbagent.view.web;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iqiyi.dbagent.base.i.ISqlMonitorServer;
/**
* 
* @Title: SqlMonitorServer.java
* @Package com.iqiyi.dbagent.view.web
* @Description: sql监控
* @author wangnianming
* @date 2016年1月13日 下午5:07:19
* @version V1.0
 */
public class SqlMonitorServer implements ISqlMonitorServer{

    private static final Logger logger  = LoggerFactory.getLogger(SqlMonitorServer.class);

    private Server server = null;
    
    private Integer port = null;
    
    public SqlMonitorServer(){
        
    }
    public static void main(String[] args) {
        new SqlMonitorServer(new Server(),8090).startMonitor();
    }

    public void startMonitor(){
        if(null == this.server){
            logger.error("server 为空!");
            return;
        }
        if(port == null){
            logger.error("请设置访问端口!");
            return;
        }
        Connector connector = new SelectChannelConnector();
		connector.setPort(this.port);
		this.server.setConnectors(new Connector[] { connector });
		WebAppContext webAppContext = new WebAppContext("WebContent","/dbAgent");
		//webAppContext.setContextPath("/");
		webAppContext.setDescriptor("WebContent/WEB-INF/web.xml");
		webAppContext.setResourceBase("WebContent");
		webAppContext.setDisplayName("dbAgent");
		webAppContext.setClassLoader(Thread.currentThread().getContextClassLoader());
		webAppContext.setConfigurationDiscovered(true);
		webAppContext.setParentLoaderPriority(true);
		server.setHandler(webAppContext);
		logger.info(webAppContext.getContextPath());
		logger.info(webAppContext.getDescriptor());
		logger.info(webAppContext.getResourceBase());
		logger.info(webAppContext.getBaseResource().toString());
		try {
			server.start();
			logger.info("server:{} is  start",server);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    /**
     * 
     */
    public void stopMonitor() {
        if(null!=this.server){
            try {
                Thread.sleep(30*1000);
                this.server.stop();
                logger.info("server:{} is stop",server);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            logger.info("no server will stop!");
        }
    }

    public Server getServer() {
        return server;
    }

    public void setServer(Server server) {
        this.server = server;
    }

    public int getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public SqlMonitorServer(Server server, Integer port) {
        super();
        this.server = server;
        this.port = port;
    }

}